package com.jackeysun.common.text

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.text.style.ImageSpan


/**
 *   Created by sunxunchao on 2022/1/6.
 */
class CenterImageSpan(context: Context, bitmap: Bitmap, verticalAlignment: Int = ALIGN_FONT_CENTER) :
    ImageSpan(context, bitmap, verticalAlignment) {

    companion object {
        const val ALIGN_FONT_CENTER = 2
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence?,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
//        super.draw(canvas, text, start, end, x, top, y, bottom, paint)
        val drawable = drawable //调用imageSpan中的方法获取drawable对象
        canvas.save()
        //获取画笔的文字绘制时的具体测量数据
        val fm = paint.fontMetricsInt
        //系统原有方法，默认是Bottom模式)
        var transY = bottom - drawable.bounds.bottom
        if (mVerticalAlignment == ALIGN_BASELINE) {
            transY -= fm.descent
        } else if (mVerticalAlignment == ALIGN_FONT_CENTER) {    //此处加入判断， 如果是自定义的居中对齐
            //与文字的中间线对齐（这种方式不论是否设置行间距都能保障文字的中间线和图片的中间线是对齐的）
            transY = ((y + fm.descent) + (y + fm.ascent)) / 2 - drawable.bounds.bottom / 2
        }
        canvas.translate(x, transY.toFloat())
        drawable.draw(canvas)
        canvas.restore()
    }
}